package com.hugoo.rpt.busz;

import com.hugoo.core.Conf;
import com.hugoo.core.ConfigurationError;
import com.hugoo.core.db.ResultPack;
import com.hugoo.core.util.TL;
import com.hugoo.rpt.ParamError;
import com.hugoo.rpt.RptPageInfo;
import com.hugoo.rpt.TextPageInfo;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

/**
 * com.hugoo.aqt.buzz.pge.HtmlGenAction
 *
 * @author Hugoo.Chan
 */
public class HtmlGenAction extends RptPageInfo implements TextPageInfo {

    int cp, tp;
    public int ps, total;
    private int _col_num;
    private boolean no_split = false, x_split = false;
    private StringBuilder sb = new StringBuilder();

    public void cacl() {
        tp = total % ps == 0 ? total / ps : total / ps + 1;
        cp = cp > tp ? tp : cp;
    }

    public HtmlGenAction(String sid, HttpServletRequest request) throws ParamError, ConfigurationError {
        super(sid, request);
        ///////////处理页面尺寸大小/////////////////////
        String _ps = request.getParameter(PS);
        if (TL.isNaN(_ps)) {
            _ps = Conf.getAutqProp(_sid, Conf.RPT._rpt_htm_pagesize);
        }
        ps = Integer.parseInt(_ps);
        if (ps == 0) {
            ps = 2000;
            no_split = true;
        } else if (ps == -1) {
            x_split = true;
            no_split = true;
        }
        /////////////处理当前页//////////////////////
        String _cp = request.getParameter(CP);
        if (TL.isNaN(_cp)) {
            _cp = "1";
        }
        cp = Integer.parseInt(_cp);
        //--
        String cl = getCustomColnum();
        if (TL.isNaN(cl)) {
            _col_num = col[0].length;//本处更改为同声明列数
        } else {
            _col_num = Integer.parseInt(cl);
        }
    }

    public String getQueryRowsSql() {
        String sql = "SELECT COUNT(1) AS CT FROM (" + super.getQuerySql() + ")";
        return sql;
    }

    /**
     * 重新包装查询语句，增加分页效果
     *
     * @return
     */
    @Override
    public String getQuerySql() {
        String sql;
        if (x_split) {
            return super.getQuerySql();
        }
        if (cp == 1) {//(cp - 1) * ps
            sql = "select * from (" + super.getQuerySql() + ") where rownum <= " + cp * ps;
        } else {
            sql = "select * from (select row_.*,rownum rownum_ from (" + super.getQuerySql()
                    + " ) row_ where rownum <= " + cp * ps + ") where rownum_> " + (cp - 1) * ps;
        }
        return sql;
    }

    protected String getCustomThead() {
        return Conf.getAutqProp2(_sid, Conf.RPT._rpt_htm_custom_thead);//读取自定义表头部分
    }

    private String getCustomColnum() {
        return Conf.getAutqProp2(_sid, Conf.RPT._rpt_htm_custom_colnum);//读取自定义列
    }

    private String getSortColumns() {
        String st = Conf.getAutqProp2(_sid, Conf.RPT._rpt_htm_sort_cols);//读取可排序列
        return this.fmt_init(st);
    }

    private String getFRMBColumns() {
        String st = Conf.getAutqProp2(_sid, Conf.RPT._rpt_htm_frmb_cols);//读取钱
        return this.fmt_init(st);
    }

    private String getFPCTColumns() {
        String st = Conf.getAutqProp2(_sid, Conf.RPT._rpt_htm_fpct_cols);//读取百分数
        return this.fmt_init(st);
    }

    private String getFNUMColumns() {
        String st = Conf.getAutqProp2(_sid, Conf.RPT._rpt_htm_fnum_cols);//读取整数
        return this.fmt_init(st);
    }

    private String fmt_init(String st) {
        if (st == null) {
            st = "";
        } else {
            st = "," + st + ",";
        }
        return st;
    }

    protected String getCustomTbodyTpl() {
        return Conf.getAutqProp2(_sid, Conf.RPT._rpt_htm_custom_tbody_tpl);//读取自定义
    }

    /**
     * **
     * 计算列头排序标识
     *
     * @param sc
     * @param v
     * @return
     */
    private char decl_sort_flag(char v) {
        for (int i = 0; i < _sort_col.length - 1; i = i + 2) {
            if (_sort_col[i] == v) {
                switch (_sort_col[i + 1]) {
                    case '0'://平->升
                        return '1';
                    case '1'://升->降
                        return '2';
                    case '2'://降->平
                        return '0';
                    default:
                        return '1';
                }
            }
        }
        return '0';
    }

    protected String _gen_thead() {
        StringBuilder st = new StringBuilder();
        String tmp = getCustomThead();
        char c = 'A';
        if (TL.isEmpty(tmp)) {
            st.append("<thead>");
            String sc = getSortColumns();
            for (int i = 0; i < col[0].length; i++) {//用于高级分析用，本部分暂时只设置为26字母有效性
                st.append("<th  ");
                if (sc.indexOf("," + col[0][i] + ",") > 0) {
                    st.append("sc='").append(decl_sort_flag(c)).append("'");
                }
                c++;
                st.append(">").append(col[1][i]).append("</th>");
            }
            st.append("</thead>");
        } else {
            String tpl;
            for (int i = 0; i < col[0].length; i++) {//用于高级分析用，本部分暂时只设置为26字母有效性
                tpl = "\\$s\\{" + col[0][i] + "\\}";
                tmp = tmp.replaceAll(tpl, " sc='" + decl_sort_flag(c) + "' ");
                c++;
            }
            st.append(tmp);//需要解决自定义标题部分的列属性问题
        }
        return st.toString();
    }

    protected String _gen_empty_tr() {
        StringBuilder st = new StringBuilder();
        sb.append("<tbody><tr>");
        for (int i = 0; i < _col_num; i++) {
            st.append("<td >&nbsp;</td>");
        }
        st.append("</tr></tbody>");
        return st.toString();
    }

    protected String _gen_empty_tfoot() {
        StringBuilder st = new StringBuilder();
        st.append("<tfoot>");
        st.append("<tr><td colspan='").append(_col_num).append("'><div id='gpg' unselectable='on' onselectstart='return false;'>"
                + "<div class='x_b_g'><span  class='span_dsbl'>暂无查询到相关记录!</span></div></div></td></tr>");
        st.append("</tfoot>");
        return st.toString();
    }

    protected String _gen_no_split_tfoot() {
        StringBuilder st = new StringBuilder();

        st.append("<tfoot>");
        st.append("<tr><td colspan='").append(_col_num).append("'><div id='gpg' unselectable='on' onselectstart='return false;'>"
                + "<div class='x_b_g'><span  class='span_dsbl'>总计").append(total).
                append("条记录</span></div><div class='x_b_g'><span class='span_dsbl'>数据导出:</span><span cmd='et' title='文本格式导出'>TXT</span><span cmd='ex' title='Excel格式导出'>XLS</span>"
                + "</div></div></td></tr>");
        st.append("</tfoot>");
        return st.toString();
    }

    protected String _gen_tfoot() {
        StringBuilder st = new StringBuilder();
        st.append("<tfoot>");
        st.append("<tr><td colspan='").append(_col_num).append("'><div id='gpg' unselectable='on' onselectstart='return false;'>"
                + "<div class='x_r'><div class='x_b_g'>");
        if (cp == 1) {
            st.append("<span class='span_dsbl'>首页</span><span class='span_dsbl'>上一页</span>");
        } else {
            st.append("<span cmd='gf' class='cmmd' cp='1' >首页</span><span class='cmmd' cp='").append(cp - 1).
                    append("' cmd='prev' >上一页</span>");
        }
        if (cp == tp) {
            st.append("<span class='span_dsbl'>下一页</span><span class='span_dsbl'>末页</span>");
        } else {
            st.append("<span class='cmmd' cmd='nxt'cp='").append(cp + 1).append("' >下一页</span><span class='cmmd' cmd='gl' cp='").
                    append(tp).append("' >末页</span>");
        }
        st.append("</div></div><div class='x_b_g'><span  class='span_dsbl'>总计").append(total).
                append("条记录，【<input id='x_psx_x' type='text' size='1' value='").append(ps).
                append("'/>条/页】【第<input type='text' id='x_cp_x' value='").append(cp).append("' size='1'/>页/共").append(tp).append("页】"
                + "</span><span cmd='gg'>跳转</span></div><div class='x_b_g'><span class='span_dsbl'>导出:</span><span cmd='ex' title='Excel格式导出'>XLS</span><span cmd='et' title='文本格式导出'>TXT</span>"
                + "</div></div></td></tr>");
        st.append("</tfoot>");
        return st.toString();
    }

    protected String _gen_tfoot_other() {
        return "";
    }

    @Override
    public ResultPack getResultPack() {
        return new ResultPack() {
            @Override
            public void packResult(ResultSet rs) {
                char r;
                try {
                    validateColumn(rs.getMetaData());//验证列,暂不启用
                    /////////////////生成报表头部/////////////////////////////////
                    sb.append("<table id='").append(_sid).append("'   _cp='").append(cp).append("' _ps='").
                            append(ps).append("' _tp='").append(tp).append("'  _tt='").append(total).append("' "
                            + "cellSpacing='0' cellPadding='1' border='0'>");
                    //   sb.append("<caption>").append(getTitleCmd()).append("</caption>");
                    /////////////////表头部处理/////////////
                    sb.append(_gen_thead());
                    /////////////////无记录时，表身的处理////////////
                    if (total == 0) {
                        sb.append(_gen_empty_tr());//生成空行记录
                        sb.append(_gen_empty_tfoot());//生成空行记录
                        sb.append("</table>");
                        return;//无相关记录
                    }
                    sb.append("<tbody _coln='").append(_col_num).append("'>");
                    String tpl = getCustomTbodyTpl();//表身部分
                    String _rs_1, _rs_2;
                    ////---------------------------------------------------//////
                    String frmb = getFRMBColumns();
                    String fpct = getFPCTColumns();
                    String fnum = getFNUMColumns();
                    int s = col[0].length;
                    boolean[] m = new boolean[col[0].length], p = new boolean[col[0].length], n = new boolean[col[0].length];
                    for (int z = 0; z < s; z++) {
                        _rs_1 = "," + col[0][z] + ",";
                        m[z] = frmb.contains(_rs_1);
                        p[z] = fpct.contains(_rs_1);
                        n[z] = fnum.contains(_rs_1);
                    }
                    ////---------------------------------------------------//////
                    if (TL.isEmpty(tpl)) {//不存在行记录模板的情况
                        while (rs.next()) {
                            sb.append("<tr>");
                            for (int z = 0; z < s; z++) {
                                _rs_1 = getValue(rs, col[0][z]);
                                sb.append("<td  title='").append(_rs_1).append("'");
                                if (columnStyle.containsKey(col[0][z])) {
                                    sb.append(" class='").append(columnStyle.get(col[0][z])).append("'");
                                }
                                if (m[z]) {//RMB
                                    sb.append(" align='right'>").append(getValue(rs, col[0][z], 'r')).append("</td>");
                                } else if (p[z]) {//百分比
                                    sb.append(" align='right'>").append(getValue(rs, col[0][z], 'p')).append("</td>");
                                } else if (n[z]) {//数值
                                    sb.append(" align='right'>").append(getValue(rs, col[0][z], 'n')).append("</td>");
                                } else {
                                    sb.append(">").append(_rs_1).append("</td>");
                                }
                            }
                            sb.append("</tr>");
                        }
                    } else {//存在行记录模板的情况
                        String tmp = tpl;
                        String[] ref_col = getRefCol();
                        while (rs.next()) {
                            tpl = tmp;
                            for (int z = 0; z < s; z++) {
                                _rs_1 = getValue(rs, col[0][z]);
                                if (m[z]) {//RMB
                                    _rs_2 = getValue(rs, col[0][z], 'r');
                                } else if (p[z]) {//百分比处理
                                    _rs_2 = getValue(rs, col[0][z], 'p');
                                } else if (n[z]) {//数值处理
                                    _rs_2 = getValue(rs, col[0][z], 'n');
                                } else {
                                    _rs_2 = null;
                                }
                                if (_rs_2 == null) {
                                    _rs_2 = " title='" + _rs_1 + "'>" + _rs_1;
                                } else {
                                    _rs_2 = " align='right' title='" + _rs_1 + "'>" + _rs_2;
                                }
                                tpl = tpl.replaceAll(">\\$\\{" + col[0][z] + "\\}", _rs_2);
                                tpl = tpl.replaceAll("\\$\\{" + col[0][z] + "\\}", _rs_1);
                            }
                            for (String c : ref_col) {//处理额外引用列部分
                                tpl = tpl.replaceAll("\\$\\{" + c + "\\}", getValue(rs, c));//$o{xx}
                            }
                            sb.append(tpl);
                        }
                    }
                    sb.append("</tbody>");

                } catch (Exception ex) {
                    log.warn("处理生成HTML代码时，出现SQL异常！", ex);
                    ex.printStackTrace(System.err);
                }
                ///////////////////////////////////处理表尾部分///////
                if (no_split) {
                    sb.append(_gen_no_split_tfoot());
                } else {
                    sb.append(_gen_tfoot());
                }

                /////////////////////////////////////////////////////
                sb.append("</table>");
            }
        };
    }

    @Override
    public String getTextInfo() {
//        String style = "<style>" + Conf.getAutqProp(_sid, Conf._rpt_htm_style) + "</style>";
//        sb.insert(0, style);
        return sb.toString();
    }

    @Override
    protected String getDeclareColumnInfo() {
        return Conf.getAutqProp2(_sid, Conf.RPT._rpt_htm_columns);
    }

    protected String[] getRefCol() {
        String x = Conf.getAutqProp2(_sid, Conf.RPT._rpt_htm_ref_columns);
        if (TL.isEmpty(x)) {
            return new String[0];
        }
        List<String> ls = new ArrayList();
        String[] s = x.split(",");
        for (String c : s) {
            if (TL.isEmpty(c)) {
                continue;
            }
            ls.add(c);
        }
        String[] rc = ls.toArray(new String[0]);
        return rc;
    }
}
